import React, {MouseEvent, useEffect, useState} from "react";
import styles from "./index.less"
import {musicArrayType} from "@/common/components/ZmMusicPlayer";
import {Howl} from "howler";

export interface MusicProgressBarProps {
    musicObj: musicArrayType | undefined,
    seekMusic?: (val: number) => void
}

const MusicProgressBar: React.FC<MusicProgressBarProps> = (props) => {
    const [barWidth, setBarWidth] = useState<string>()
    const [musicProgressTime, setMusicProgressTime] = useState<string>()
    const [musicDuration, setMusicDuration] = useState<string>()
    let offSetX = 0;
    const formatTime = (secs: number) => {
        let minutes = Math.floor(secs / 60) || 0;
        let seconds = (secs - minutes * 60) || 0;

        return minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
    }
    const updateProgress = (value: Howl) => {
        let width = (((value.seek() / value.duration()) * 100) || 0) + 'px';
        let time = formatTime(Math.round(value.seek()))
        setMusicProgressTime(time)
        setBarWidth(width)
        if (value.playing()) {
            requestAnimationFrame(updateProgress.bind(this, value));
        }
    }
    const onMouseUpDragProgressbar = (e: MouseEvent) => {
        if (props.musicObj?.musicObj.duration()) {
            const time = Math.round(e.nativeEvent.offsetX / 100 * props.musicObj?.musicObj.duration())
            if (props.seekMusic) props.seekMusic(time)
        }
    }
    useEffect(() => {
        if (!props?.musicObj) return;
        props.musicObj.musicObj.on("play", () => {
            if (props.musicObj?.musicObj) {
                setMusicDuration(formatTime(Math.round(props.musicObj?.musicObj.duration())));
                requestAnimationFrame(updateProgress.bind(this, props.musicObj?.musicObj))
            }
        })
    }, [props.musicObj]);
    return (
        <>
            <div className={styles["music-progress-bar-time"]}>
                <span>{musicProgressTime}</span><span>{musicDuration}</span>
            </div>
            <div className={styles["music-progress-bar-box"]}
                 onMouseUp={onMouseUpDragProgressbar}>
                <div className={styles["music-progress-bar"]} style={{width: barWidth}}></div>
            </div>
        </>

    )
}
export default MusicProgressBar;